package dao;

import model.Order;
import util.OrderCodeUtil; // 引入 OrderCodeUtil
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OrderDaoImpl implements OrderDao { // 订单数据访问实现 完成人：姜凯严、邓亦明 7/5
    private static final String DB_URL = "jdbc:sqlite:redwine.db";

    @Override
    public boolean addOrder(Order order) { // 添加订单
        String sql = "INSERT INTO 'order' (user_id, redwine_id, quantity, status, online, code) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(DB_URL);
                PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setInt(1, order.getUserId());
            pstmt.setInt(2, order.getRedWineId());
            pstmt.setInt(3, order.getQuantity());
            pstmt.setString(4, order.getStatus().name());
            pstmt.setInt(5, order.isOnline() ? 1 : 0);
            pstmt.setInt(6, order.getCode());
            int affected = pstmt.executeUpdate();
            if (affected > 0) {
                ResultSet rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    order.setOrderId(rs.getInt(1));
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean updateOrder(Order order) { // 修改订单
        // ... (保持不变，已包含事务逻辑) ...
        String sql = "UPDATE 'order' SET user_id=?, redwine_id=?, quantity=?, status=?, online=?, code=? WHERE order_id=?";

        // 先获取原订单信息，用于计算库存差值
        Order originalOrder = findOrder(order.getOrderId()); //
        if (originalOrder == null) {
            return false; // 原订单不存在
        }

        try (Connection conn = DriverManager.getConnection(DB_URL)) {
            // 开启事务
            conn.setAutoCommit(false);

            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setInt(1, order.getUserId());
                pstmt.setInt(2, order.getRedWineId());
                pstmt.setInt(3, order.getQuantity());
                pstmt.setString(4, order.getStatus().name());
                pstmt.setInt(5, order.isOnline() ? 1 : 0);
                pstmt.setInt(6, order.getCode());
                pstmt.setInt(7, order.getOrderId());

                int affected = pstmt.executeUpdate();
                if (affected > 0) {
                    // 检查是否需要更新库存
                    boolean needUpdateStock = (originalOrder.getQuantity() != order.getQuantity()) ||
                            (originalOrder.getRedWineId() != order.getRedWineId());

                    if (needUpdateStock) {
                        // 如果红酒ID改变了，需要恢复原红酒库存并减少新红酒库存
                        if (originalOrder.getRedWineId() != order.getRedWineId()) {
                            // 恢复原红酒库存
                            String updateOriginalStockSql = "UPDATE redwine SET stock = stock + ? WHERE redwine_id = ?";
                            try (PreparedStatement updateOriginalPstmt = conn
                                    .prepareStatement(updateOriginalStockSql)) {
                                updateOriginalPstmt.setInt(1, originalOrder.getQuantity());
                                updateOriginalPstmt.setInt(2, originalOrder.getRedWineId());
                                updateOriginalPstmt.executeUpdate();
                            }

                            // 减少新红酒库存
                            String updateNewStockSql = "UPDATE redwine SET stock = stock - ? WHERE redwine_id = ?";
                            try (PreparedStatement updateNewPstmt = conn.prepareStatement(updateNewStockSql)) {
                                updateNewPstmt.setInt(1, order.getQuantity());
                                updateNewPstmt.setInt(2, order.getRedWineId());
                                updateNewPstmt.executeUpdate();
                            }
                        } else {
                            // 同一红酒，只需要调整库存差值
                            int quantityDiff = order.getQuantity() - originalOrder.getQuantity();
                            if (quantityDiff != 0) {
                                String updateStockSql = "UPDATE redwine SET stock = stock - ? WHERE redwine_id = ?";
                                try (PreparedStatement updateStockPstmt = conn.prepareStatement(updateStockSql)) {
                                    updateStockPstmt.setInt(1, quantityDiff);
                                    updateStockPstmt.setInt(2, order.getRedWineId());
                                    updateStockPstmt.executeUpdate();
                                }
                            }
                        }
                    }

                    // 提交事务
                    conn.commit();
                    return true;
                } else {
                    // 回滚事务
                    conn.rollback();
                    return false;
                }
            } catch (SQLException e) {
                // 回滚事务
                conn.rollback();
                throw e;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean deleteOrder(int orderId) { // 删除订单
        String sql = "DELETE FROM 'order' WHERE order_id=?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, orderId);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Order findOrder(int orderId) { // 根据订单ID查找订单
        String sql = "SELECT order_id, user_id, redwine_id, quantity, status, online, code FROM 'order' WHERE order_id=?";
        try (Connection conn = DriverManager.getConnection(DB_URL);
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, orderId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                Order order = new Order();
                order.setOrderId(rs.getInt("order_id"));
                order.setUserId(rs.getInt("user_id"));
                order.setRedWineId(rs.getInt("redwine_id"));
                order.setQuantity(rs.getInt("quantity"));
                order.setStatus(Order.OrderStatus.valueOf(rs.getString("status")));
                order.setOnline(rs.getInt("online") == 1);
                order.setCode(rs.getInt("code"));
                return order;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Order> findAll() { // 查询所有订单
        List<Order> list = new ArrayList<>();
        String sql = "SELECT order_id, user_id, redwine_id, quantity, status, online, code FROM 'order'";
        try (Connection conn = DriverManager.getConnection(DB_URL);
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                Order order = new Order();
                order.setOrderId(rs.getInt("order_id"));
                order.setUserId(rs.getInt("user_id"));
                order.setRedWineId(rs.getInt("redwine_id"));
                order.setQuantity(rs.getInt("quantity"));
                order.setStatus(Order.OrderStatus.valueOf(rs.getString("status")));
                order.setOnline(rs.getInt("online") == 1);
                order.setCode(rs.getInt("code"));
                list.add(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int addOrdersBatchAndUpdateStocks(List<Order> newOrders, Map<Integer, Integer> redWineStockChanges) {
        if (newOrders == null || newOrders.isEmpty() || redWineStockChanges == null || redWineStockChanges.isEmpty()) {
            return -1; // 无有效订单或库存变化，直接返回失败
        }

        Connection conn = null;
        int generatedCode = -1;
        try {
            conn = DriverManager.getConnection(DB_URL); //
            conn.setAutoCommit(false); // 开启事务

            // 1. 生成 8 位标识码
            generatedCode = OrderCodeUtil.generateUniqueOrderCode(findAll()); //

            // 2. 批量插入订单
            String insertOrderSql = "INSERT INTO 'order' (user_id, redwine_id, quantity, status, online, code) VALUES (?, ?, ?, ?, ?, ?)";
            try (PreparedStatement pstmt = conn.prepareStatement(insertOrderSql)) {
                for (Order order : newOrders) {
                    order.setCode(generatedCode); // 为每个订单设置统一的标识码
                    pstmt.setInt(1, order.getUserId());
                    pstmt.setInt(2, order.getRedWineId());
                    pstmt.setInt(3, order.getQuantity());
                    pstmt.setString(4, order.getStatus().name());
                    pstmt.setInt(5, order.isOnline() ? 1 : 0);
                    pstmt.setInt(6, order.getCode());
                    pstmt.addBatch(); // 添加到批处理
                }
                pstmt.executeBatch(); // 执行批量插入
            }

            // 3. 批量更新红酒库存
            String updateStockSql = "UPDATE redwine SET stock = stock - ? WHERE redwine_id = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(updateStockSql)) {
                for (Map.Entry<Integer, Integer> entry : redWineStockChanges.entrySet()) {
                    int redWineId = entry.getKey();
                    int quantityToDeduct = entry.getValue();

                    // 可以在这里再次检查库存，但通常会在业务逻辑层（UI或Service）完成初步检查
                    // 这里只是执行扣减，假设传入的数量是合理的
                    pstmt.setInt(1, quantityToDeduct);
                    pstmt.setInt(2, redWineId);
                    pstmt.addBatch(); // 添加到批处理
                }
                pstmt.executeBatch(); // 执行批量更新
            }

            conn.commit(); // 提交事务
            return generatedCode; // 返回成功生成的标识码
        } catch (SQLException e) {
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback(); // 发生异常时回滚事务
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            return -1; // 失败返回-1
        } finally {
            if (conn != null) {
                try {
                    conn.close(); // 关闭连接
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean updateOrdersStatusByCode(int orderCode, Order.OrderStatus newStatus) {
        String sql = "UPDATE 'order' SET status = ? WHERE code = ?";
        try (Connection conn = DriverManager.getConnection(DB_URL); //
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, newStatus.name());
            pstmt.setInt(2, orderCode);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}